<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>数据概览</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="6" v-for="(item, index) in overviewData" :key="index">
          <div class="data-card">
            <div class="card-title">{{ item.title }}</div>
            <div class="card-value">{{ item.value }}</div>
            <div class="card-desc">{{ item.desc }}</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>数据类型分布</span>
          </div>
          <div id="typeDistributionChart" style="width: 100%; height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>告警类型分布</span>
          </div>
          <div id="alarmTypeChart" style="width: 100%; height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="box-card" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span>数据趋势分析</span>
        <div class="filter-container">
          <el-radio-group v-model="trendTimeRange" size="small" @change="fetchDataTrend">
            <el-radio-button label="day">今日</el-radio-button>
            <el-radio-button label="week">本周</el-radio-button>
            <el-radio-button label="month">本月</el-radio-button>
            <el-radio-button label="year">本年</el-radio-button>
          </el-radio-group>
          <el-select
            v-model="trendDataType"
            placeholder="数据类型"
            clearable
            size="small"
            style="width: 120px"
            @change="fetchDataTrend"
          >
            <el-option v-for="item in dataTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-select
            v-model="trendDeviceId"
            placeholder="设备"
            clearable
            size="small"
            style="width: 120px"
            @change="fetchDataTrend"
          >
            <el-option v-for="item in deviceOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </div>
      <div id="trendChart" style="width: 100%; height: 400px"></div>
    </el-card>

    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>数据量排行</span>
          </div>
          <div id="dataRankingChart" style="width: 100%; height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>告警量排行</span>
          </div>
          <div id="alarmRankingChart" style="width: 100%; height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="box-card" style="margin-top: 20px">
      <div slot="header" class="clearfix">
        <span>数据质量分析</span>
        <div class="filter-container">
          <el-date-picker
            v-model="qualityTimeRange"
            type="daterange"
            align="right"
            size="small"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="fetchQualityAnalysis"
          />
          <el-select
            v-model="qualityDataType"
            placeholder="数据类型"
            clearable
            size="small"
            style="width: 120px"
            @change="fetchQualityAnalysis"
          >
            <el-option v-for="item in dataTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </div>
      <el-row :gutter="20">
        <el-col :span="6" v-for="(item, index) in qualityData" :key="index">
          <div class="data-card">
            <div class="card-title">{{ item.title }}</div>
            <div class="card-value">{{ item.value }}</div>
            <div class="card-desc">{{ item.desc }}</div>
          </div>
        </el-col>
      </el-row>
      <div id="qualityChart" style="width: 100%; height: 300px; margin-top: 20px"></div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getDataOverview, getDataTypeDistribution, getDataTrend, getDeviceRanking, getDataQualityAnalysis } from '@/api/data'
import { getAlarmStatistics } from '@/api/data'
import { getDeviceList } from '@/api/device'

export default {
  name: 'DataStatistics',
  data() {
    return {
      // 概览数据
      overviewData: [],
      
      // 趋势图筛选条件
      trendTimeRange: 'day',
      trendDataType: '',
      trendDeviceId: '',
      
      // 质量分析筛选条件
      qualityTimeRange: [],
      qualityDataType: '',
      qualityData: [],
      
      // 图表实例
      typeDistributionChart: null,
      alarmTypeChart: null,
      trendChart: null,
      dataRankingChart: null,
      alarmRankingChart: null,
      qualityChart: null,
      
      // 选项数据
      dataTypeOptions: [
        { value: 'temperature', label: '温度' },
        { value: 'humidity', label: '湿度' },
        { value: 'pressure', label: '压力' },
        { value: 'flow', label: '流量' },
        { value: 'level', label: '液位' }
      ],
      deviceOptions: [],
      
      // 日期选择器配置
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  created() {
    this.fetchData()
    this.fetchDeviceOptions()
  },
  mounted() {
    this.initCharts()
    
    // 监听窗口大小变化，调整图表大小
    window.addEventListener('resize', this.resizeCharts)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts)
    
    // 销毁图表实例
    this.typeDistributionChart && this.typeDistributionChart.dispose()
    this.alarmTypeChart && this.alarmTypeChart.dispose()
    this.trendChart && this.trendChart.dispose()
    this.dataRankingChart && this.dataRankingChart.dispose()
    this.alarmRankingChart && this.alarmRankingChart.dispose()
    this.qualityChart && this.qualityChart.dispose()
  },
  methods: {
    // 初始化所有图表
    initCharts() {
      this.typeDistributionChart = echarts.init(document.getElementById('typeDistributionChart'))
      this.alarmTypeChart = echarts.init(document.getElementById('alarmTypeChart'))
      this.trendChart = echarts.init(document.getElementById('trendChart'))
      this.dataRankingChart = echarts.init(document.getElementById('dataRankingChart'))
      this.alarmRankingChart = echarts.init(document.getElementById('alarmRankingChart'))
      this.qualityChart = echarts.init(document.getElementById('qualityChart'))
    },
    
    // 调整图表大小
    resizeCharts() {
      this.typeDistributionChart && this.typeDistributionChart.resize()
      this.alarmTypeChart && this.alarmTypeChart.resize()
      this.trendChart && this.trendChart.resize()
      this.dataRankingChart && this.dataRankingChart.resize()
      this.alarmRankingChart && this.alarmRankingChart.resize()
      this.qualityChart && this.qualityChart.resize()
    },
    
    // 获取所有数据
    fetchData() {
      this.fetchOverview()
      this.fetchTypeDistribution()
      this.fetchDataTrend()
      this.fetchDeviceRanking()
      this.fetchQualityAnalysis()
      this.fetchAlarmStatistics()
    },
    
    // 获取设备选项
    fetchDeviceOptions() {
      getDeviceList({ pageSize: 100 }).then(response => {
        if (response.code === 200) {
          this.deviceOptions = response.data.data.map(item => {
            return { value: item.id, label: item.name }
          })
        }
      })
    },
    
    // 获取概览数据
    fetchOverview() {
      getDataOverview().then(response => {
        if (response.code === 200) {
          const data = response.data
          this.overviewData = [
            { title: '今日数据量', value: data.today_count, desc: `昨日：${data.yesterday_count}` },
            { title: '本周数据量', value: data.week_count, desc: `上周：${data.last_week_count}` },
            { title: '本月数据量', value: data.month_count, desc: `上月：${data.last_month_count}` },
            { title: '总数据量', value: data.total_count, desc: `告警率：${data.alarm_rate}%` }
          ]
        }
      })
    },
    
    // 获取数据类型分布
    fetchTypeDistribution() {
      getDataTypeDistribution().then(response => {
        if (response.code === 200) {
          const data = response.data
          
          // 更新数据类型分布图
          this.typeDistributionChart.setOption({
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
              orient: 'vertical',
              right: 10,
              top: 'center',
              data: data.map(item => item.name)
            },
            series: [
              {
                name: '数据类型',
                type: 'pie',
                radius: ['50%', '70%'],
                avoidLabelOverlap: false,
                label: {
                  show: false,
                  position: 'center'
                },
                emphasis: {
                  label: {
                    show: true,
                    fontSize: '18',
                    fontWeight: 'bold'
                  }
                },
                labelLine: {
                  show: false
                },
                data: data.map(item => {
                  return { value: item.count, name: item.name }
                })
              }
            ]
          })
        }
      })
    },
    
    // 获取告警类型分布
    fetchAlarmStatistics() {
      getAlarmStatistics().then(response => {
        if (response.code === 200) {
          const data = response.data.type_stats
          
          // 更新告警类型分布图
          this.alarmTypeChart.setOption({
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
              orient: 'vertical',
              right: 10,
              top: 'center',
              data: data.map(item => this.getAlarmTypeText(item.alarm_type))
            },
            series: [
              {
                name: '告警类型',
                type: 'pie',
                radius: ['50%', '70%'],
                avoidLabelOverlap: false,
                label: {
                  show: false,
                  position: 'center'
                },
                emphasis: {
                  label: {
                    show: true,
                    fontSize: '18',
                    fontWeight: 'bold'
                  }
                },
                labelLine: {
                  show: false
                },
                data: data.map(item => {
                  return { value: item.count, name: this.getAlarmTypeText(item.alarm_type) }
                })
              }
            ]
          })
          
          // 更新告警排行榜
          this.alarmRankingChart.setOption({
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              }
            },
            legend: {
              data: ['告警数量']
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'value',
              boundaryGap: [0, 0.01]
            },
            yAxis: {
              type: 'category',
              data: response.data.device_top.map(item => item.name)
            },
            series: [
              {
                name: '告警数量',
                type: 'bar',
                data: response.data.device_top.map(item => item.count)
              }
            ]
          })
          
          // 更新趋势图
          const trend = response.data.trend
          this.trendChart.setOption({
            tooltip: {
              trigger: 'axis'
            },
            legend: {
              data: ['数据量', '告警量']
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              boundaryGap: false,
              data: trend.map(item => item.date)
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                name: '告警量',
                type: 'line',
                stack: '总量',
                data: trend.map(item => item.count),
                areaStyle: {},
                emphasis: {
                  focus: 'series'
                },
                itemStyle: {
                  color: '#F56C6C'
                }
              }
            ]
          })
        }
      })
    },
    
    // 获取数据趋势
    fetchDataTrend() {
      const params = {
        time_range: this.trendTimeRange
      }
      
      if (this.trendDataType) {
        params.data_type = this.trendDataType
      }
      
      if (this.trendDeviceId) {
        params.device_id = this.trendDeviceId
      }
      
      getDataTrend(params).then(response => {
        if (response.code === 200) {
          const data = response.data
          
          // 更新趋势图
          let seriesData = [
            {
              name: '数据量',
              type: 'line',
              stack: '总量',
              smooth: true,
              data: data.data_count,
              areaStyle: {},
              emphasis: {
                focus: 'series'
              },
              itemStyle: {
                color: '#409EFF'
              }
            }
          ]
          
          // 如果有告警数据，添加告警系列
          if (data.alarm_count) {
            seriesData.push({
              name: '告警量',
              type: 'line',
              stack: '总量',
              smooth: true,
              data: data.alarm_count,
              areaStyle: {},
              emphasis: {
                focus: 'series'
              },
              itemStyle: {
                color: '#F56C6C'
              }
            })
          }
          
          this.trendChart.setOption({
            tooltip: {
              trigger: 'axis'
            },
            legend: {
              data: seriesData.map(item => item.name)
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              boundaryGap: false,
              data: data.time_points
            },
            yAxis: {
              type: 'value'
            },
            series: seriesData
          })
        }
      })
    },
    
    // 获取设备排行
    fetchDeviceRanking() {
      getDeviceRanking().then(response => {
        if (response.code === 200) {
          const data = response.data
          
          // 更新数据量排行榜
          this.dataRankingChart.setOption({
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              }
            },
            legend: {
              data: ['数据数量']
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '3%',
              containLabel: true
            },
            xAxis: {
              type: 'value',
              boundaryGap: [0, 0.01]
            },
            yAxis: {
              type: 'category',
              data: data.data_ranking.map(item => item.name)
            },
            series: [
              {
                name: '数据数量',
                type: 'bar',
                data: data.data_ranking.map(item => item.count)
              }
            ]
          })
        }
      })
    },
    
    // 获取数据质量分析
    fetchQualityAnalysis() {
      const params = {}
      
      if (this.qualityTimeRange && this.qualityTimeRange.length === 2) {
        params.start_time = this.formatDate(this.qualityTimeRange[0])
        params.end_time = this.formatDate(this.qualityTimeRange[1])
      }
      
      if (this.qualityDataType) {
        params.data_type = this.qualityDataType
      }
      
      getDataQualityAnalysis(params).then(response => {
        if (response.code === 200) {
          const data = response.data
          
          // 更新质量指标
          this.qualityData = [
            { title: '总数据量', value: data.total_count, desc: '' },
            { title: '有效数据量', value: data.valid_count, desc: '' },
            { title: '完整率', value: data.integrity_rate + '%', desc: '' },
            { title: '告警率', value: data.alarm_rate + '%', desc: '' }
          ]
          
          // 更新质量分析图
          const alarmTypeData = data.alarm_types.map(item => {
            return { value: item.count, name: this.getAlarmTypeText(item.type) }
          })
          
          this.qualityChart.setOption({
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
              orient: 'horizontal',
              bottom: 10,
              data: alarmTypeData.map(item => item.name)
            },
            series: [
              {
                name: '告警类型',
                type: 'pie',
                radius: ['30%', '50%'],
                avoidLabelOverlap: false,
                label: {
                  show: false,
                  position: 'center'
                },
                emphasis: {
                  label: {
                    show: true,
                    fontSize: '18',
                    fontWeight: 'bold'
                  }
                },
                labelLine: {
                  show: false
                },
                data: alarmTypeData
              }
            ]
          })
        }
      })
    },
    
    // 获取告警类型文本
    getAlarmTypeText(type) {
      const types = {
        1: '超出上限',
        2: '低于下限',
        3: '数据异常',
        4: '连接断开',
        5: '其他'
      }
      return types[type] || '未知'
    },
    
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    }
  }
}
</script>

<style scoped>
.data-card {
  padding: 20px;
  text-align: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  height: 100px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.card-desc {
  font-size: 12px;
  color: #606266;
}

.filter-container {
  float: right;
  margin-top: -5px;
}
</style> 